package cn.crex1.xiaomi.service.impl;

import cn.crex1.xiaomi.common.UserStatusEnum;
import cn.crex1.xiaomi.dao.UserDao;
import cn.crex1.xiaomi.dao.impl.UserDaoImpl;
import cn.crex1.xiaomi.service.UserService;
import cn.crex1.xiaomi.util.JsonUtils;
import cn.crex1.xiaomi.util.RedisUtil;
import cn.crex1.xiaomi.util.StringUtil;
import cn.crex1.xiaomi.vo.UserVO;

public class UserServiceImpl implements UserService {
	
	private static String uToken = "utoken";
	
	private UserDao userDao = new UserDaoImpl();
//登录
	@Override
	public String selectUserByTelephoneAndPassword(UserVO uservo) {
		if (uservo.getTelephone()!=null && uservo.getPassword()!=null) {
			if (RedisUtil.Keys.exists(uToken+uservo.getTelephone())) {
				return UserStatusEnum.ALREADYLOGIN.getDesc();
			}else {
				int userid = userDao.selectOsUserByTelephoneAndPassword(uservo);
				if (userid!=0) {
					//创建用户token
					String token = StringUtil.token();
					//存入redis
					RedisUtil.Strings.set(token+"+"+userid, userid+"+"+uservo.getTelephone());
					RedisUtil.Strings.set(uToken+uservo.getTelephone(), token+"+"+userid);
					RedisUtil.Keys.expired(uToken+uservo.getTelephone(), 86400);
					RedisUtil.Keys.expired(token+"+"+userid, 86400);
					return token+"+"+userid;
				}else {
					return UserStatusEnum.ACCOUNTERROR.getDesc();
				}
			}
		}	
		return null;
	}
	
	

//注册
	@Override
	public String updateUserByUserNameAndPasswordAndTelephone(UserVO uservo) {
		if(uservo.getTelephone()!=null&&uservo.getPassword()!=null&&uservo.getUsername()!=null) {
			int userid = userDao.updateOsUserByTelephoneAndPassword(uservo);
			if (userid!=0) {
				return "成功";
			}else {
				return "失败";
			}
		}
		return null;
	}
	//查询账户是否已经注册
	@Override
	public String selectUserByUserName(UserVO uservo) {
		if(uservo.getUsername()!=null) {
			int userid=userDao.selectOsUserByUserName(uservo);
			if(userid!=0){
				return "已注册";
			}else{
				return "未注册";
			}
		}
		return null;
	}
	//查询手机号是否已经注册
	@Override
	public String selectUserByTelephone(UserVO uservo) {
		if(uservo.getTelephone()!=null) {
			int userid=userDao.selectOsUserByTelephone(uservo);
			if(userid!=0){
				return "已使用";
			}else{
				return "未使用";
			}
		}
		return null;
	}

	@Override
	public String selectUsernameByUserId(Integer userId) {	
		return userDao.selectUsernameByUserId(userId);
	}



	@Override
	public Long selectTelephoneByUserId(Integer userId) {
		return userDao.selectTelephoneByUserId(userId);
	}
	
}
